export default async function (source, params, headers) {
  const query = new URLSearchParams(params)
  const response = await fetch(
    (headers.baseURL || '') + '/special-work/shouxianWorkTicket/getShouXianFormInfo?' + query,
    {
      method: 'get',
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
        ...(headers || {})
      }
    }
  )

  if (response.status !== 200 || !response.ok) {
    // 尝试读取错误信息
    const errorText = await response.text()
    console.error('API请求失败:', {
      status: response.status,
      statusText: response.statusText,
      url: response.url,
      responseText: errorText
    })
    return null
  }

  // 检查响应内容类型
  const contentType = response.headers.get('content-type')
  if (!contentType || !contentType.includes('application/json')) {
    const text = await response.text()
    console.error('响应不是JSON格式:', text)
    return null
  }

  try {
    const data = await response.json()
    if (data.success) {
      return fillData(source, data.data)
    } else {
      return null
    }
  } catch (error) {
    console.error('JSON解析失败:', error)
    return null
  }
}

function fillData(source, data) {
  // console.log(source, data, '444444444444')

  if (data && Object.keys(data).length > 0) {
    source[0].header[0].value = data.licenseId

    source[0].data[0][0].value = data.applicantUnitName
    source[0].data[0][1].value = data.workApproveTime
    source[0].data[1][0].value = data.spaceName
    source[0].data[1][1].value = data.mediumName
    source[0].data[2][0].value = data.shouxianDesc
    source[0].data[3][0].value = data.operationalUnitName
    source[0].data[3][1].value = data.personInCharge
    source[0].data[4][0].value = data.operator
    source[0].data[4][1].value = data.guardian
    source[0].data[5][0].value = data.otherWorkLicenseId
    source[0].data[6][0].value = data.identConsequence?.join(',')

    // TODO : 气体分析，先暂时缓一缓，业务有点复杂

    if (data.shouxianEstStartTime && data.shouxianEstEndTime) {
      source[0].data[7][0].data[5][0].value =
        data.shouxianEstStartTime + '至' + data.shouxianEstEndTime
    } else if (!data.shouxianEstStartTime && data.shouxianEstEndTime) {
      source[0].data[7][0].data[5][0].value = data.shouxianEstEndTime + '止'
    } else if (data.shouxianEstStartTime && !data.shouxianEstEndTime) {
      source[0].data[7][0].data[5][0].value = data.shouxianEstStartTime + '起'
    } else {
      source[0].data[7][0].data[5][0].value = ''
    }

    source[0].data[7][0].data[6][0].data.list =
      data.workSafeMeasuresVOS?.map((pm, ind) => {
        return [
          ind + 1,
          pm.measures,
          ['否', '是'][pm.isInvole / 1],
          {
            text: pm.signPersonName,
            mode: 'img',
            modeUrl: pm.sign,
            modeStyle: {
              margin: 'auto'
            },
            modeConfig: {
              title: pm.signPersonName
            }
          }
        ]
      }) || []

    source[0].data[7][0].data[7][0].data[0][0].value = data.workSafeDisclosureVOS?.join('、')
    source[0].data[7][0].data[7][0].data[0][1].value = data.safeAcceptDisclosureVOS?.join('、')

    source[0].data[7][0].data[8][0].data =
      data.approveInfoVOS?.map((pm) => {
        return {
          label: pm.approveNode,
          value: pm.approveOpinion,
          sign: pm.approveSign,
          signMode: 'img',
          signTitle: pm.approvePersonName,
          time: pm.approveTime
        }
      }) || []
    if (data.workCheckAcceptRecordVO) {
      source[0].data[7][0].data[8][0].data.push({
        label: '完工验收',
        value: ['同意', '拒绝'][data.workCheckAcceptRecordVO.checkAcceptResult / 1],
        sign: data.workCheckAcceptRecordVO.sign,
        signMode: 'img',
        signTitle: data.workCheckAcceptRecordVO.checkAcceptPersonName,
        time: data.workCheckAcceptRecordVO.signTime
      })
    }

    // 最复杂的气体分析来了 0-4
    if (data.sxAssembleGasVO && Object.keys(data.sxAssembleGasVO).length > 0) {
      const gastd = source[0].data[7][0].data

      // 气体分析整个跨行
      gastd[0][0].labelConfig.rowspan =
        3 +
        (data.sxAssembleGasVO.analysisData.length < 2
          ? 2
          : data.sxAssembleGasVO.analysisData.length)

      // 有毒有害气体垮列
      const dh_ary = data.sxAssembleGasVO.standard.toxicAnalysis
      gastd[0][2].labelConfig.colspan = dh_ary.length < 2 ? 2 : dh_ary.length

      // 可燃气体垮列
      const kr_ary = data.sxAssembleGasVO.standard.combustibleAnalysis
      gastd[0][3].labelConfig.colspan = kr_ary.length < 2 ? 2 : kr_ary.length

      // 分析气体总列树
      source[0].data[7][0].columnsNum =
        gastd[0][2].labelConfig.colspan + gastd[0][3].labelConfig.colspan + 6

      // gastd[1] =
      const dh_bz = [...dh_ary]
        .slice(0, Math.max(dh_ary.length, 2))
        .concat(new Array(Math.max(2 - dh_ary.length, 0)).fill(null))

      const kr_bz = [...kr_ary]
        .slice(0, Math.max(kr_ary.length, 2))
        .concat(new Array(Math.max(2 - kr_ary.length, 0)).fill(null))

      gastd[1] = dh_bz.concat(kr_bz).map((k) => {
        return { label: k ? k.gasSpecies : '' }
      })
      gastd[2] = dh_bz.concat(kr_bz).map((k) => {
        return { label: k ? k.eligibility : '' }
      })
      gastd[2].push({ label: '19.5%~21%(体积分数)' })
      gastd[2].unshift({ label: '合格标准' })

      // 分析数据：需要将数据拆分成第一行和其他行
      const gasAnaFirst = data.sxAssembleGasVO.analysisData[0]
      const unit = ['', '%', '%LEL', 'ppm', 'mg/m³', '其他']
      const type = ['', 'combustibleAnalysis', 'toxicAnalysis', 'oxygenAnalysis']
      gastd[3] = dh_bz.concat(kr_bz).map((k) => {
        if (!k) return { labelHtml: '&nbsp;', label: '' }
        const g = gasAnaFirst[type[k.gasCategory]]?.find((p) => p.gasSpecies === k.gasSpecies)
        if (!g) return { labelHtml: '&nbsp;', label: '' }
        return { label: g.gasContent + unit[g.gasUnit] }
      })
      gastd[3].unshift({
        label: '分析数据',
        labelConfig: { rowspan: gastd[0][0].labelConfig.rowspan - 3 }
      })
      gastd[3].push(
        ...[
          {
            label: '',
            labelHtml:
              (gasAnaFirst.oxygenAnalysis &&
                gasAnaFirst.oxygenAnalysis[0]?.gasContent +
                  unit[gasAnaFirst.oxygenAnalysis[0]?.gasUnit]) ||
              ''
          },
          { label: gasAnaFirst.analysisDate },
          { label: gasAnaFirst.analysisPart },
          { label: gasAnaFirst.analysisPerson }
        ]
      )

      let fx_res = data.sxAssembleGasVO.analysisData.slice(1)
      if (fx_res && fx_res.length > 0) {
        fx_res = fx_res.map((m) => {
          const ntr = dh_bz.concat(kr_bz).map((k) => {
            if (!k) return { labelHtml: '&nbsp;', label: '' }
            const g = m[type[k.gasCategory]]?.find((p) => p.gasSpecies === k.gasSpecies)
            if (!g) return { labelHtml: '&nbsp;', label: '' }
            return { label: g.gasContent + unit[g.gasUnit] }
          })
          ntr.push(
            ...[
              {
                label: '',
                labelHtml:
                  (m.oxygenAnalysis &&
                    m.oxygenAnalysis[0]?.gasContent + unit[m.oxygenAnalysis[0]?.gasUnit]) ||
                  '&nbsp;'
              },
              { label: m.analysisDate },
              { label: m.analysisPart },
              { label: m.analysisPerson }
            ]
          )

          return ntr
        })
        gastd.splice(4, 1, ...fx_res) // 把索引为4的行删除，加入新的行数组
      } else {
        gastd[4] = Array(gastd[3].length - 1).fill({ labelHtml: '&nbsp;', label: '' })
      }
    }
  }

  return source
}
